<?php
namespace wap\models;

use Yii;
use yii\base\Model;

/**
 * Signin form
 *
 * @property $username
 * @property $vcode
 * @property $password
 */
class SigninForm extends Model
{
    public $username;
    public $vcode;
    public $password;

    private $_user;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required', 'message' => '请输入手机号码'],
            ['username', 'match', 'pattern' => '/^1[3-9][0-9]{9}$/'],

            ['vcode', 'trim'],

            ['password', 'string', 'min' => 6],
        ];
    }

    public function attributeLabels()
    {
        return [
            'mobile' => '手机号码',
            'vcode' => '验证码',
            'password' => '密码',
        ];
    }

    /**
     * 登陆验证
     *
     * @return \api\models\User|bool|null
     */
    public function signin()
    {
        if($this->validate()){
            $user = $this->getUser();
            if($user){
                if($this->vcode){
                    $vcode = Yii::$app->cache->get('api_vcode_' . $this->username);
                    if($vcode != $this->vcode){
                        return '验证码错误！';
                    }
                }else if(!$user->validatePassword($this->password)){
                    return '密码错误！';
                }

                return $user;
            }
        }

        return '手机号码不存在！';
    }

    /**
     * 通过手机获取用户
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = Users::findByMobile($this->username);
        }

        return $this->_user;
    }
}
